package co.fitstart.mobile.web.controller.auth;

import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.handler.CookieHandler;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.entity.user.User;
import co.fitstart.entity.user.UserAccount;
import co.fitstart.mobile.Constant;
import co.fitstart.mobile.entity.UserContext;
import co.fitstart.mobile.handler.SmsSender;
import co.fitstart.mobile.service.UserService;
import co.fitstart.mobile.web.resolver.Secure;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("")
public class LoginController {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    private static final String SAVED_REQUEST = "MOBILE_SNIFFER_SAVED_REQUEST";
    
    @Autowired
    private CookieHandler cookieHandler;
    
    @Autowired
    private SmsSender smsSender;
    
    @Autowired
    private UserService userService;

    /**
     * Goes to login page
     * 
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String mobileLogin() {
        return "auth/login";
    }
    
    @RequestMapping(value = "/login", method = RequestMethod.GET, params="email")
    public String emailLogin() {
        return "auth/login-email";
    }
    
    /**
     * 
     * @param mobile
     * @param code
     * @param token
     * @param userContext
     * @param httpSession
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody String onMobileLogin(@RequestParam("mobile") String mobile, 
                                              @RequestParam("code") String code, 
                                              @RequestParam("token") String token,
                                              UserContext userContext,
                                              HttpSession httpSession,
                                              HttpServletRequest request,
                                              HttpServletResponse response) {
        
        Result result = new Result();
        
        try {
            
            // Gets saved request from http session
            String originalUrl = (String) httpSession.getAttribute(SAVED_REQUEST);
            if(StringUtils.isNoneBlank(originalUrl)) originalUrl = URLDecoder.decode(originalUrl, "UTF-8");
            
            // check verify code first 
            boolean valid = smsSender.checkVerifyCode(mobile, code, token);

            if(valid) {
                
                String openid = userContext.getOpenid();
                String cookieAccountId = userContext.getAccountId();
                
                // 1. check userContext 
                if((StringUtils.isNotEmpty(openid) && StringUtils.isNotBlank(openid)) && (StringUtils.isEmpty(cookieAccountId) || StringUtils.isBlank(cookieAccountId))) {
                    logger.warn("LoginController#onMobileLogin login with cookie openid [{}], but cookieAccountId is empty. please check the wechatAuthorityInteceptor", openid);
                }
                
                // 2. do login with mobile, openid, accountId
                logger.info("LoginController#onMobileLogin login with mobile [{}] openid [{}] accountId [{}]", mobile, openid, cookieAccountId);
                UserAccount userAccount = userService.login(mobile, openid, cookieAccountId, false);
                if(userAccount == null) {
                    throw new BusinessException("用户手机账号保存失败");
                }
                
                // 3. add mobile & userAccount id into cookie
                String mobileAccountId = String.valueOf(userAccount.getId());
                if(StringUtils.isNotEmpty(mobileAccountId) && StringUtils.isNotBlank(mobileAccountId)) {
                    cookieHandler.addCookie(response, Constant.USER_ACCOUNT_KEY, mobileAccountId, 7200);
                }
                cookieHandler.addCookie(response, Constant.MOBILE_KEY, mobile, 7200);
                
                result.success().message("登录成功").data("redirect", StringUtils.isBlank(originalUrl) ? WebUtils.getRealServerPath(request) + "/profile" : originalUrl);
                
            } else {
                
                result.fail().message("验证码不正确");
            }
            
            
        } catch (Exception e) {
            logger.error("LoginController#onMobileLogin() error", e);
            result.fail().message("绑定手机失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param mailbox
     * @param userContext
     * @param httpSession
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, params="email")
    public @ResponseBody String onEmailLogin(@RequestParam("mailbox") String mailbox, 
                               UserContext userContext,
                               HttpSession httpSession,
                               HttpServletResponse response) {

        Result result = new Result();
        
        try {
            // Gets saved request from http session
            String originalUrl = (String) httpSession.getAttribute(SAVED_REQUEST);
            if(StringUtils.isNoneBlank(originalUrl)) originalUrl = URLDecoder.decode(originalUrl, "UTF-8");

            String openid = userContext.getOpenid();
            String accountId = userContext.getAccountId();
            
            // 1. check userContext 
            if((StringUtils.isNotEmpty(openid) && StringUtils.isNotBlank(openid)) && (StringUtils.isEmpty(accountId) || StringUtils.isBlank(accountId))) {
                logger.warn("LoginController#onEmailLogin login with cookie openid [{}], but accountId is empty. please check the wechatAuthorityInteceptor", openid);
            }
            
            // 2. do login with mobile openid accountId
            logger.info("LoginController#onEmailLogin login with mailbox [{}] openid [{}] accountId [{}]", mailbox, openid, accountId);
            UserAccount userAccount = userService.login(mailbox, openid, accountId, true);
            
            // 3. add mobile & userAccount id into cookie
            accountId = String.valueOf(userAccount.getId());
            
            if(StringUtils.isNotEmpty(accountId) && StringUtils.isNotBlank(accountId)) {
                cookieHandler.addCookie(response, Constant.USER_ACCOUNT_KEY, accountId, 7200);
            }
            cookieHandler.addCookie(response, Constant.MOBILE_KEY, mailbox, 7200);
            
            result.success().message("登录成功").data("redirect", StringUtils.isBlank(originalUrl) ? "/" : originalUrl);
            
        } catch (Exception e) {
            logger.error("LoginController#onEmailLogin() error", e);
            result.fail().message("绑定手机失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param user
     * @param response
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public @ResponseBody String onLogout(@Secure() User user,
                                         HttpServletResponse response) {
        
        Result result = new Result();
        
        try {
            
//            UserAccount userAccount = userService.getUserAccount(Constant.USER_ACCOUNT_MOBILE_KEY, user.getMobile());
//            String mobileAccountId = String.valueOf(userAccount.getId());
//            if(StringUtils.isNotEmpty(mobileAccountId) && StringUtils.isNotBlank(mobileAccountId)) {
                cookieHandler.removeCookie(response, Constant.USER_ACCOUNT_KEY);
//            }
            cookieHandler.removeCookie(response, Constant.MOBILE_KEY);
            
            cookieHandler.removeCookie(response, Constant.OPENID_KEY);
            
            result.success().message("退出登录成功");
                
            
        } catch (Exception e) {
            logger.error("LoginController#onLogout() error", e);
            result.fail().message("退出登录失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    @RequestMapping(value = "/logout-message", method = RequestMethod.GET)
    public String logout() {
        return "redirect:/login";
    }
    
}
